use derive_builder::Builder;
use serde::{Deserialize, Serialize};

use crate::error::Error;
use crate::mapper::ValueMapper;
use crate::modeling::{
    Class, ClassAttributeBuilder, ClassBuilder, ClassGetter, ClassRelationBuilder,
    RelationRelatedType, ValueType,
};
use crate::modeling::{
    ClassAttributePersistence, ClassPersistence, ClassPersistenceBuilder, ClassPersistenceGetter,
    ClassRelation, ClassRelationGetter, Value,
};

use super::Model;

const MODEL_CONFIGURE_CLASS_IDENTIFIER: &'static str = "g01_model_setting";

const MODEL_CONFIGURE_CLASS_NAME: &'static str = "model_setting";

const MODEL_CONFIGURE_TABLE_NAME: &'static str = "_g01_meta_model_setting";

#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
#[builder(name = "ModelSettingBuilder")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option), default)]
#[builder(derive(Debug))]
#[builder(build_fn(error = "Error"))]
pub struct ModelSetting {
    /// id
    pub id: i64,
    ///
    pub model_identifier: String,
    ///
    pub is_valid: bool,
    /// encrypted_config
    pub encrypted_config: Option<String>,
    /// credential_schema
    pub credential_schema_identifier: Option<String>,
    /// 选项
    pub options: Option<String>,
    /// 创建时间
    pub created_at: i64,
    /// 更新时间
    pub updated_at: i64,
}

impl ValueMapper for ModelSetting {}
//
crate::impl_from_value!(ModelSetting);
crate::impl_class_persistence_getter!(ModelSetting, MODEL_CONFIGURE_TABLE_NAME);
crate::impl_class_relations_getter!(
    ModelSetting,
    vec![ClassRelationBuilder::default()
        .src_identifier(Model::get_identifier()?)
        .target_identifier(Self::get_identifier()?)
        .related_type(RelationRelatedType::Keys)
        .related_at("default_model")
        .build()?,]
);

impl ClassGetter for ModelSetting {
    fn get_name() -> anyhow::Result<String> {
        Ok(String::from(MODEL_CONFIGURE_CLASS_NAME))
    }
    fn get_identifier() -> anyhow::Result<String> {
        Ok(String::from(MODEL_CONFIGURE_CLASS_IDENTIFIER))
    }
    fn get_class() -> anyhow::Result<Class> {
        let mut attribute_builder = ClassAttributeBuilder::default();
        attribute_builder.class_identifier(MODEL_CONFIGURE_CLASS_IDENTIFIER);

        let mut commons = crate::modeling::simple_attributes_with_builder(&attribute_builder)?;
        let mut append = vec![
            attribute_builder
                .clone()
                .name("model_identifier")
                .title("模型")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("is_valid")
                .title("是否有效")
                .data_type(ValueType::Boolean)
                .build()?,
            attribute_builder
                .clone()
                .name("encrypted_config")
                .title("配置")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("credential_schema_identifier")
                .title("配置")
                .data_type(ValueType::String)
                .build()?,
        ];
        append.append(&mut commons);
        append.sort_by(|a, b| a.position.cmp(&b.position));

        let clazz = ClassBuilder::default()
            .identifier(MODEL_CONFIGURE_CLASS_IDENTIFIER)
            .name(MODEL_CONFIGURE_CLASS_NAME)
            .data_is_type(true)
            .is_persistent(true)
            .primary_key(String::from("identifier"))
            .attributes(append)
            .build()?;
        Ok(clazz)
    }
}
